package com.tian.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;

/**
 * {@code @description:} 请求限流器，基于IP地址进行限流
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-09-02 10:16
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class RequestLimiter implements KeyResolver {
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        InetAddress address = exchange.getRequest().getRemoteAddress().getAddress();
        if (address == null) {
            return Mono.empty();
        }
        String hostAddress = address.getHostAddress();
        log.info("限流器,基于IP地址进行限流,ip地址为：{}", hostAddress);
        return Mono.just(hostAddress);
    }
}
